import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db

from pytz.gae import pytz
import rest

class Posting(db.Model):
    author = db.StringProperty(required = True)
    title = db.StringProperty(required = True)
    content = db.TextProperty(required = True)
    date = db.DateTimeProperty(auto_now_add = True)

    # main or reply
    type = db.CategoryProperty(required = True)

    # if a type of model instance is main, this field is filled
    nr_reply = db.IntegerProperty(default = 0)
    
    # If a type of model instance is reply, this field is filled
    mainThread = db.SelfReferenceProperty()

    # Still,  only QnA
    category = db.CategoryProperty(required = True)


rest.Dispatcher.base_url = "/api"
rest.Dispatcher.add_models({
    "posting": Posting
})

utc = pytz.utc
kst = pytz.timezone('Asia/Seoul')

def doRender(handler, tname="index.html", values={}):
    temp = os.path.join(os.path.dirname(__file__), 'templates/' + tname)
    if not os.path.isfile(temp):
        return False

    newval = dict(values)
    newval['path'] = handler.request.path

    result = template.render(temp, newval)
    handler.response.out.write(result)
    return True

class MainHandler(webapp.RequestHandler):
    def get(self):
        # self.response.out.write("Save My Kids\n")
        # return
        qry = db.Query(Posting)
        qry.filter('category = ', 'qna')
        qry.filter('type = ', 'main')
        posting_list = qry.fetch(limit = 20)
        for posting in posting_list:
            utc_time = utc.localize(posting.date)
            posting.date = utc_time.astimezone(kst)
        
        doRender(self, 'index.html', {'postings': posting_list})

    def post(self):
        self.response.out.write("Postings\n")

application = webapp.WSGIApplication(
    [('/api/.*', rest.Dispatcher), ('/', MainHandler)],
    debug = True)
    
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
